//
//  ViewController.m
//  BlueTooth
//
//  Created by Wdecho on 17/4/26.
//  Copyright (c) 2017年 wdTEST. All rights reserved.
//

#import "ViewController.h"
#import "JMAntiLostAes128.h"
#import <AVFoundation/AVFoundation.h>
#define MyDeviceName @"zmkm_keyfob"//zmkm_keyfob   zmkm  advzmkm....
#define startID @"aa550606ff01"// APP开始寻找防丢器指令

#define  STRAA @"0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a01020304050607080900102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a01020304050607080900102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a01020304050607080900102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a01020304050607080900102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a01020304050607080900102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a01020304050607080900102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a01020304050607080900102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a01020304050607080900102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a01020304050607080900102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a01020304050607080900102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a01020304050607080900102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090"
#define stopID  @"aa550606ff00"// App停止寻找防丢器指令
#define blueToappID @"aa5506ffff0200000000000000000000" // 防丢器寻找app 指令解密的字符串


@interface ViewController ()<AVAudioPlayerDelegate>

@property (nonatomic, strong) CBCentralManager *centralMgr;
@property (nonatomic, strong) CBPeripheral *discoveredPeripheral;
// 连接外设的写服务特征
@property (nonatomic, strong) CBCharacteristic *writeCharacteristic;
//  订阅服务特征
@property (nonatomic,strong) CBCharacteristic * notifyCharacteristic;
//读取服务特征
@property (nonatomic,strong) CBCharacteristic * readCharacteristic;
@property (weak, nonatomic) IBOutlet UITextField *editText;
@property (weak, nonatomic) IBOutlet UILabel *resultText;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;

@property (nonatomic,strong)NSData *testData;
@property (nonatomic,strong) NSMutableArray *array;

// 播放音乐

@property (nonatomic,strong) AVAudioPlayer *audioPlayer;


@property (nonatomic,strong) NSString *str1;
@property (nonatomic,strong) NSString *str2;
@property (nonatomic,strong) NSString *str3;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];// aa5506ff01  aa5506ff02
    self.view.alpha = 0.5;
    
     _editText.text =[NSString stringWithFormat:STRAA];
    self.centralMgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    _testData =[NSData data];
    _array =[NSMutableArray arrayWithCapacity:10000];
}
- (IBAction)startSech:(UIButton *)sender {
    self.view.alpha= 1;
}

//检查App的设备BLE是否可用 （ensure that Bluetooth low energy is supported and available to use on the central device）
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state)
    {
        case CBCentralManagerStatePoweredOn:
            //discover what peripheral devices are available for your app to connect to
            //第一个参数为CBUUID的数组，需要搜索特点服务的蓝牙设备，只要每搜索到一个符合条件的蓝牙设备都会调用didDiscoverPeripheral代理方法
            [self.centralMgr scanForPeripheralsWithServices:nil options:nil];
            break;
        default:
            NSLog(@"Central Manager did change state");
            break;
    }
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    //找到需要的蓝牙设备，停止搜素，保存数据
    if([peripheral.name isEqualToString:MyDeviceName]){
        _discoveredPeripheral = peripheral;
        [_centralMgr connectPeripheral:peripheral options:nil];
        _nameLabel.text = [NSString stringWithFormat:@"%@",peripheral.name];
    }
//    if ([peripheral.identifier.UUIDString isEqualToString:Identifier]) {
//        _discoveredPeripheral = peripheral;
//        [_centralMgr connectPeripheral:peripheral options:nil];
//    }
}

//连接成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{

    [_discoveredPeripheral setDelegate:self];
    //discover all of the services that a peripheral offers,搜索服务,回调didDiscoverServices
    [_discoveredPeripheral discoverServices:nil];
    [_centralMgr stopScan];
}

//当监听到失去和外围设备连接，重新建立连接
//这个方法是必须实现的，因为蓝牙会中断连接，正好触发这个方法重建连接。重建连接可能造成数秒后才能读取到RSSI。

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    [_centralMgr connectPeripheral:peripheral options:nil];
}
//连接失败，就会得到回调：
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    //此时连接发生错误
    NSLog(@"connected periphheral failed");
}

//获取服务后的回调
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    if (error)
    {
        NSLog(@"didDiscoverServices : %@", [error localizedDescription]);
        return;
    }
    
    for (CBService *s in peripheral.services)
    {
        NSLog(@"Service found with UUID : %@", s.UUID);
        //Discovering all of the characteristics of a service,回调didDiscoverCharacteristicsForService
        [s.peripheral discoverCharacteristics:nil forService:s];
    }
}


- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(nullable NSError *)error
{
    if (error)
    {
        NSLog(@"didDiscoverCharacteristicsForService error : %@", [error localizedDescription]);
        return;
    }
    
    for (CBCharacteristic *c in service.characteristics)
    {
        
        switch (c.properties) {
            case CBCharacteristicPropertyBroadcast:
                NSLog(@"CBCharacteristicPropertyBroadcast");
                break;
            case CBCharacteristicPropertyRead:
                NSLog(@"CBCharacteristicPropertyRead");
                // 保存读的特征
                self.readCharacteristic = c;
                [peripheral readValueForCharacteristic:c];
                break;
            case CBCharacteristicPropertyWriteWithoutResponse:
                NSLog(@"CBCharacteristicPropertyWriteWithoutResponse");
                // 保存写的特征
                self.writeCharacteristic = c;
                break;
            case CBCharacteristicPropertyWrite:
                NSLog(@"CBCharacteristicPropertyWrite");
                // 保存写的特征
                self.writeCharacteristic = c;
                break;
            case CBCharacteristicPropertyNotify:
                NSLog(@"CBCharacteristicPropertyNotify");
                [peripheral setNotifyValue:YES forCharacteristic:c];
                // 保存订阅的特征
                self.notifyCharacteristic = c;
                [peripheral setNotifyValue:YES forCharacteristic:c];
                //peripheral:didUpdateNotificationStateForCharacteristic:error:
                break;
            case CBCharacteristicPropertyIndicate:
                [peripheral setNotifyValue:YES forCharacteristic:c];
                 // 保存订阅的特征
                self.notifyCharacteristic = c;
                NSLog(@"CBCharacteristicPropertyIndicate");
                //peripheral:didUpdateNotificationStateForCharacteristic:error:
                break;
            case CBCharacteristicPropertyAuthenticatedSignedWrites:
                // 保存写的特征
                self.writeCharacteristic = c;
                NSLog(@"CBCharacteristicPropertyAuthenticatedSignedWrites");
                break;
            case CBCharacteristicPropertyExtendedProperties:
                NSLog(@"CBCharacteristicPropertyExtendedProperties");
                break;
            case CBCharacteristicPropertyNotifyEncryptionRequired:
                NSLog(@"CBCharacteristicPropertyNotifyEncryptionRequired");
                break;
            case CBCharacteristicPropertyIndicateEncryptionRequired:
                NSLog(@"CBCharacteristicPropertyIndicateEncryptionRequired");
                break;
            default:
                break;
        }
    }
}

//订阅的特征值有新的数据时回调
- (void)peripheral:(CBPeripheral *)peripheral
didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic
             error:(NSError *)error {
    if (error) {
        NSLog(@"Error changing notification state: %@",
              [error localizedDescription]);
    }
    [peripheral readValueForCharacteristic:characteristic];

}

// 获取到特征的值时回调 处理蓝牙传输过来的数据
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    if (error)
    {
        NSLog(@"didUpdateValueForCharacteristic error : %@", error.localizedDescription);
        return;
    }
    
     // <ee13e026 201328e6 aae54892 12acd371>
     // <b46360c7 bbff34d5 5a4c3c32 5c01bdad>
    
      NSData *data = characteristic.value;
      NSData *data1  =[JMAntiLostAes128 antiLostAes128Decrypt:data];
    
    NSData *zuihouD = [data1 subdataWithRange:NSMakeRange(data1.length-2, 2)];
     NSLog(@"%@",zuihouD);
     _resultText.text =  [NSString stringWithFormat:@"%@",[self convertDataToHexStr:data1]];
     [_array addObject:[self convertDataToHexStr:data1]];
    
      NSLog(@"aaaaa%@",_array);
    
    if ([_resultText.text isEqualToString:blueToappID]) {
        // 播放 音乐
        [self startPlay];
    }
}

// 播放音乐
-(void)startPlay{
    // 1.获取要播放音频文件的URL
    NSURL *fileURL = [[NSBundle mainBundle]URLForResource:@"yanyuan" withExtension:@".mp3"];
    // 2.创建 AVAudioPlayer 对象
    self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:nil];
    // 3.设置循环播放
    self.audioPlayer.numberOfLoops = -1;
    self.audioPlayer.delegate = self;
    // 4.准备开始播放
    [self.audioPlayer prepareToPlay];
    [self.audioPlayer play];
}

- (IBAction)stopPlay:(UIButton *)sender {
    
    [self.audioPlayer pause];
}


// nsadata 转16进制字符串
- (NSString *)convertDataToHexStr:(NSData *)data {
    if (!data || [data length] == 0) {
        return @"";
    }
    
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    
    return string;
}

#pragma mark 写数据
-(void)writeChar:(NSData *)data
{
    //回调didWriteValueForCharacteristic
    [_discoveredPeripheral writeValue:data forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithResponse];
}

#pragma mark 写数据后回调
- (void)peripheral:(CBPeripheral *)peripheral
didWriteValueForCharacteristic:(CBCharacteristic *)characteristic
             error:(NSError *)error {
    if (error) {
        NSLog(@"Error writing characteristic value: %@",
              [error localizedDescription]);
        return;
    }
    NSLog(@"写入%@成功",characteristic);
}

#pragma mark 发送按钮点击事件
- (IBAction)sendClick:(id)sender {
    [self rangString:_editText.text];
//    // 字符串转Data
//    NSData *data =  [self convertHexStrToData:STRAA];
//    
//    NSMutableData *sendData = [JMAntiLostAes128 antiLostAes128Encrypt:data];
//    
//    [self writeChar:sendData];
}

-(void)rangString:(NSString *)str{
    for (int i =0; i < str.length/32 +1; i ++) {
        if (i >0) {
            // 判断剩余的字符串的长度
            if (_str3.length == 0) {
                return;
            }
            if (_str3.length < 32) {
                _str1 =_str3;
                NSData *data =  [self convertHexStrToData:_str1];
                NSMutableData *sendData = [JMAntiLostAes128 antiLostAes128Encrypt:data];
                NSLog(@"%@",sendData);
                [self writeChar:sendData];
                NSLog(@"%d",i);
                return;
            }
        }
        // 要截取的字符串 一次性截取16位
        NSString *interceptStr =[str substringWithRange:NSMakeRange(i *32, 32)];
        _str1 = interceptStr;
        // 剩余的字符串
        NSString *surplusStr =[str substringFromIndex:(i+1)*32];
        _str3 = surplusStr;
        // 字符串转Data
        NSData *data =  [self convertHexStrToData:_str1];
        NSMutableData *sendData = [JMAntiLostAes128 antiLostAes128Encrypt:data];
          NSLog(@"%d%@",i,sendData);
        [self writeChar:sendData];
    }
}

// 16进制转化为NSData
- (NSData *)convertHexStrToData:(NSString *)str {
    if (!str || [str length] == 0) {
        return nil;
    }
    NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];
    NSRange range;
    if ([str length] % 2 == 0) {
        range = NSMakeRange(0, 2);
    } else {
        range = NSMakeRange(0, 1);
    }
    for (NSInteger i = range.location; i < [str length]; i += 2) {
        unsigned int anInt;
        NSString *hexCharStr = [str substringWithRange:range];
        NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
        [scanner scanHexInt:&anInt];
        NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
        [hexData appendData:entity];
        range.location += range.length;
        range.length = 2;
    }
    NSLog(@"hexdata: %@", hexData);
    return hexData;
}
- (IBAction)stopClick:(UIButton *)sender {
    // 写入停止寻找的命令
    NSData *data =  [self convertHexStrToData:STRAA];
    //Byte *data = {0x07,0x00};
    NSMutableData *sendData = [JMAntiLostAes128 antiLostAes128Encrypt:data];
    NSLog(@"%@",sendData);
    [self writeChar:sendData];
}


@end
